package com.usian.service.impl;

import com.usian.CatNode;
import com.usian.CatResult;
import com.usian.mapper.TbItemCatMapper;
import com.usian.pojo.TbItemCat;
import com.usian.pojo.TbItemCatExample;
import com.usian.redis.RedisClient;
import com.usian.service.ItemCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class ItemCategoryServiceImpl implements ItemCategoryService {

    @Autowired
    private TbItemCatMapper tbItemCatMapper;

    @Value("${PROTAL_CATRESULT_KEY}")
    private String PROTAL_CATRESULT_KEY;

    @Autowired
    private RedisClient redisClient;

    @Override
    public List<TbItemCat> selectItemCategoryByParentId(Long id) {
        TbItemCatExample example = new TbItemCatExample();
        TbItemCatExample.Criteria criteria = example.createCriteria();
        criteria.andStatusEqualTo(1).andParentIdEqualTo(id);

        List<TbItemCat> tbItemCatList = tbItemCatMapper.selectByExample(example);
        return tbItemCatList;
    }

    @Override
    public CatResult selectItemCategoryAll() {
        CatResult catResult = new CatResult();
//        去redis缓存查询
        catResult = (CatResult)redisClient.get(PROTAL_CATRESULT_KEY);
        if (catResult!=null){
            return catResult;
        }

        catResult.setData(this.getCatList(0L));
        //        缓存redis
        redisClient.set(PROTAL_CATRESULT_KEY,catResult);
        return catResult;
    }

    public List<?> getCatList(Long parrentId){
        TbItemCatExample example = new TbItemCatExample();
        TbItemCatExample.Criteria criteria = example.createCriteria();
        criteria.andParentIdEqualTo(parrentId);
        List<TbItemCat> itemCatList = tbItemCatMapper.selectByExample(example);

        ArrayList CatList = new ArrayList();
        int count = 0;

        for (TbItemCat tbItemCat : itemCatList) {
//            true==1  false==0
            if (tbItemCat.getIsParent()) {
//                1：将当前节点数据封装到CatNode
                CatNode catNode = new CatNode();
                catNode.setName(tbItemCat.getName());
//                2：递归查询子节点
                catNode.setItem(getCatList(tbItemCat.getId()));
                CatList.add(catNode);
                count++;
//                只取商品分类的18条数据
                if (count==18){
                    break;
                }
            }else {
                CatList.add(tbItemCat.getName());
            }
        }
        return CatList;
    }
}
